package com.geniusk.client;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.text.DecimalFormat;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MqttClientTest {

    public static String temp;
    public static String relay = "0";

    public static void main(String[] args) {
        String subTopic = "1524007483634454528/sub";
        String pubTopic = "1524007483634454528/pub";
        int qos = 2;
        String broker = "tcp://127.0.0.1:1883";
        String clientId = "1524007483634454528";
        String productKey = "1524007483634454528";
        String deviceSecret = "123456";
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(productKey);
            connOpts.setPassword(deviceSecret.toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);

            // 设置回调
            client.setCallback(new PushCallback());

            // 建立连接
            System.out.println("Connecting to broker: " + broker);
            client.connect(connOpts);

            System.out.println("Connected");

            // 订阅
            client.subscribe(subTopic);

            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    // 发布主题
                    JSONObject jsonObject = new JSONObject();
                    temp = generateTemp();
                    jsonObject.set("temp",temp);
                    jsonObject.set("relay",relay);
                    String content = JSONUtil.toJsonStr(jsonObject);
                    MqttMessage message = new MqttMessage(content.getBytes());
                    message.setQos(qos);
                    try {
                        client.publish(pubTopic, message);
                        System.out.println("Publishing message: " + content);
                    } catch (MqttException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("Message published");
                }
            };

            long delay = 0; // 延迟开始执行的时间，单位是毫秒，这里设置为立即开始
            long period = 1000; // 定时器执行的间隔时间，单位也是毫秒

            timer.scheduleAtFixedRate(task, delay, period);

//            client.disconnect();
//            System.out.println("Disconnected");
//            client.close();
//            System.exit(0);

        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }

    public static String generateTemp(){
        Random random = new Random();
        double min = 18;  // 设定最小温度为18°C
        double max = 24;  // 设定最大温度为24°C
        double temperature = random.nextDouble() * (max - min) + min;
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(temperature);
    }

    public static String generateHumidity(){
        Random random = new Random();
        double min = 35;  // 设定最小湿度为18°C
        double max = 40;  // 设定最大湿度为24°C
        double temperature = random.nextDouble() * (max - min) + min;
        DecimalFormat df = new DecimalFormat("#.0");
        return df.format(temperature);
    }
}
